const { Service } = require('egg')
const { tableToList } = require('../utils/tools')

module.exports = class emptyroomService extends Service {
  /**
   * 爬取空闲教室
   * @param {string} term 学期
   * @param {string} zc 周次
   * @param {string} xq 校区
   * @param {string} jxl 教学楼
   * @param {string} week 周次
   * @return {Array} *
   */
  async table(term, zc, xq, jxl, week) {
    // console.log(term, zc, xq, jxl, week);
    const Cookie = this.ctx.state.Cookie
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/kbxx/jsjy_query2`
    const res = await this.ctx.curl(apiUrl, {
      method: 'POST',
      data: {
        typewhere: 'jszq',
        xnxqh: term,
        gnq_mh: '',
        jsmc_mh: '',
        syjs0601id: '',
        xqbh: xq,
        jxqbh: '',
        jslx: '',
        jxlbh: jxl,
        jsbh: '',
        bjfh: '=',
        rnrs: '',
        jszt: '',
        zc,
        zc2: zc,
        xq: week,
        xq2: week,
        jc: '',
        jc2: '',
        kbjcmsid: '94673FF3230E4769E0533C41FF0A2703',
      },
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
      timeout: 10000,
    })
    const table = {}
    if (res.status === 200) {
      try {
        const tableList = tableToList(res.data.toString(), '#dataList')
        const data = tableList.splice(3)
        const period1 = ['1', '3', '5', '7', '9']
        const period2 = ['2', '4', '6', '8', '10']
        for (let i = 0; i < period1.length; i++) {
          table[period1[i]] = []
          table[period2[i]] = []
          for (let j = 0; j < data.length; j++) {
            if (data[j][i + 1] === '') {
              table[period1[i]].push(data[j][0].replace(/\((.*?)\)/, ''))
              table[period2[i]].push(data[j][0].replace(/\((.*?)\)/, ''))
            }
          }
        }
        return table
      } catch (err) {
        console.log('err', err)
        throw err
      }
    }
    return table
  }
}
